<template>
  <div class="sticky top-0 z-10 bg-white dark:bg-zinc-900">
    <ul
      class="relative flex items-center overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
      ref="ulTarget"
    >
      <!-- 滑块 -->
      <li
        class="absolute h-[22px] bg-zinc-900 dark:bg-zinc-800 rounded-lg duration-200 z-[-1]"
        :style="sliderStyle"
      ></li>
      <!-- 汉堡按钮 -->
      <li
        class="fixed top-[0.25rem] right-[-1px] px-1 py-1 shrink-0 bg-white shadow-l-white dark:bg-zinc-900 dark:shadow-l-zinc"
        @click="onClickOpenPopup"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
      <!-- category item -->
      <li
        :ref="setItemRef"
        v-for="(item, index) in $store.getters.categorys"
        :key="item.id"
        class="px-1 py-1 shrink-0 last:mr-4"
        :class="{ 'text-zinc-100': currentCategoryIndex === index }"
        @click="onItemClick(index)"
      >
        {{ item.name }}
      </li>
    </ul>
    <m-popup v-model="isVisable">
      <menu-vue :categorys="categoryData" @onItemClick="onItemClick"></menu-vue>
    </m-popup>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUpdate } from 'vue'
import { useScroll } from '@vueuse/core'
import MenuVue from '../../menu/index.vue'
defineProps({
  categoryData: {
    type: Array,
    required: true
  }
})

// 滑块

// 滑块
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '40px'
})

// 选中的 item 下标
const currentCategoryIndex = ref(0)
// item 点击事件
const onItemClick = (index) => {
  currentCategoryIndex.value = index
  isVisable.value = false
}

// 注意：当dom发生变化的时候，itemRefs会被不断填满重复
// 获取填充的所有 item 元素
let itemRefs = []
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}
//在 数据更改之后，Dom加载之前  清除数据
onBeforeUpdate(() => {
  itemRefs.value = []
})

// 获取 ul 元素，以计算偏移位置
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)

/**
 *  注意：如果开启了 immediate: true
 *watch的执行会提升到created之前
 执行顺序为
 watch (immediate: true)
create
beforeMount
mounted
 * */
watch(currentCategoryIndex, (val) => {
  // 获取选中元素的 left、width
  const { left, width } = itemRefs[val].getBoundingClientRect()
  // 为 sliderStyle 设置属性
  sliderStyle.value = {
    // ul 横向滚动位置 + 当前元素的 left 偏移量-ul本身左侧的paddiing 10px
    transform: `translateX(${ulScrollLeft.value + left - 10 + 'px'})`,
    width: width + 'px'
  }
})

/**
 * 打卡弹窗
 */
const isVisable = ref(false)
const onClickOpenPopup = () => {
  isVisable.value = true
}
</script>

<style lang="scss" scoped></style>
